const fs = require('fs')
const path = require('path')

const Router = require('koa-router')
const router = new Router()

// 需要递归
const loadRouters = (basePath) => {
  // 确保路径是绝对路径
  const currentPath = path.resolve(__dirname, basePath)

  // 读取目录内容（同步操作）
  const files = fs.readdirSync(currentPath)

  files.forEach((filename) => {
    const fullPath = path.join(currentPath, filename)
    const stats = fs.statSync(fullPath) // 同步获取文件状态

    if (stats.isDirectory()) {
      // 递归处理子目录（传递完整相对路径）
      loadRouters(path.relative(__dirname, fullPath))
    } else if (
      filename !== 'index.js' &&
      path.extname(filename) === '.js' // 确保是JS文件
    ) {
      // 动态导入路由模块（使用相对路径）
      const relativePath = path.relative(__dirname, fullPath)
      const r = require(`./${relativePath}`)
      router.use(r.routes())
    }
  })
}
loadRouters(__dirname)

module.exports = router
